#include "GoBang.h"
#include "ui_GoBang.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QDebug>
#include <QTimer>
#include <QTime>

GoBang::GoBang(QWidget *parent) :
    QMainWindow(parent),
    m_qipan(new qipan(this)),
    ui(new Ui::GoBang),
    gameOver(false),
    gameStart(false),
    gamePaus(false),
    remainingTime(300)  // 初始化剩余时间为5分钟
{
    ui->setupUi(this);
    setWindowTitle("五子棋");
    setFixedSize(800, 680);

    // 初始化游戏逻辑和棋盘
    initGameLogic();

    // 初始化计时器
    initTimer();

    // 设置棋盘布局
    setupLayout();

    // 设置UI元素
    setupUIElements();

    // 连接信号与槽
    connected();
}

GoBang::~GoBang()
{
    delete ui;
    delete m_qipan;
    delete m_logic;
    delete timer;
}
// 初始化游戏逻辑
void GoBang::initGameLogic()
{
    m_logic = new GameLogic;
    int boardSize = 0;
    m_qipan->getBoardInfo(boardSize);  // 获取棋盘信息
    m_logic->setQipanBoard(m_qipan->getBoardInfo(boardSize), boardSize);
}

// 初始化计时器
void GoBang::initTimer()
{
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &GoBang::updateTimer);
}

// 设置棋盘布局
void GoBang::setupLayout()
{
    QWidget *centerWidget = new QWidget(this);
    setCentralWidget(centerWidget);

    QVBoxLayout *layout = new QVBoxLayout(centerWidget);
    layout->addWidget(m_qipan);
}

// 设置UI元素的位置和显示
void GoBang::setupUIElements()
{
    // 手动设置按钮位置
    ui->start_pushbutton->setParent(this);
    ui->start_pushbutton->setGeometry(635, 190, 110, 41);

    ui->restart_pushbutton->setParent(this);
    ui->restart_pushbutton->setGeometry(635, 250, 110, 41);

    ui->renege_pushbutton->setParent(this);
    ui->renege_pushbutton->setGeometry(635, 480, 110, 41);

    ui->lcdNumber->setParent(this);
    ui->lcdNumber->setGeometry(635, 350, 110, 41);

    ui->comboBox->setParent(this);
    ui->comboBox->setGeometry(635, 70, 110, 41);

    // 设置默认显示文本
    ui->comboBox->addItem("选择模式");

    // 添加选项
    ui->comboBox->addItem("电脑对战");
    ui->comboBox->addItem("玩家对战");

    ui->comboBox->setCurrentIndex(0);

    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(ModeChanged(int)));
}


void GoBang::connected()
{
    // 信号连接
    connect(m_qipan, &qipan::ChessClick, this, &GoBang::handleChessClickSlots);
    connect(m_logic, &GameLogic::AiPostion, this, &GoBang::handleAiChessPosSlot);
    connect(ui->start_pushbutton, &QPushButton::clicked, this, &GoBang::start_pushbutton_clicked);
    connect(ui->restart_pushbutton, &QPushButton::clicked, this, &GoBang::restart_pushbutton_clicked);
    connect(ui->renege_pushbutton, &QPushButton::clicked, this, &GoBang::renege_pushbutton_clicked);
}

// 处理AI下棋的信号
void GoBang::handleAiChessPosSlot(int row, int col)
{
    qDebug() << "row:" << row << " col:" << col;
    m_qipan->setBoardInfo(row, col, COMPUTER);  // 在棋盘上设置AI的棋子
    m_qipan->update();

    saveMove(row, col, false);  // 记录AI下的棋

    // 检查AI是否获胜
    if (m_logic->checkWin(row, col, COMPUTER))
    {
        gameOver = true;
        QMessageBox::information(this, "游戏结束", "AI获胜");
        ui->start_pushbutton->setEnabled(true);  // 启用开始按钮
        ui->restart_pushbutton->setEnabled(false);  // 禁用重新开始按钮
        timer->stop();  // 停止计时器
    }
}

// 处理玩家点击棋盘的信号
void GoBang::handleChessClickSlots(int row, int col)
{
    if (gameOver)
    {
        QMessageBox::warning(this, "游戏结束", "游戏已经结束,请点击开始重新开始游戏！");
        return;
    }

    if (!gameStart)
    {
        QMessageBox::warning(this, "游戏尚未开始", "请点击开始按钮");
        return;
    }

    if (gamePaus)
    {
        QMessageBox::warning(this, "游戏已暂停", "游戏已暂停，请先恢复游戏！");
        return;
    }

    saveMove(row, col, true);  // 记录玩家下的棋

    m_qipan->setBoardInfo(row, col, PLAYER);  // 玩家下棋
    m_qipan->update();

    // 检查玩家是否获胜
    if (m_logic->checkWin(row, col, PLAYER))
    {
        QMessageBox::information(this, "游戏结束", "玩家获胜");
        gameOver = true;
        ui->start_pushbutton->setEnabled(true);  // 启用开始按钮
        ui->restart_pushbutton->setEnabled(false);  // 禁用重新开始按钮
        timer->stop();  // 停止计时器
        return;
    }

    m_logic->ComputerMove();  // AI下棋
}

// 点击开始按钮时的操作
void GoBang::start_pushbutton_clicked()
{
    qDebug() << "游戏开始";

    gameStart = true;
    gameOver = false;
    gamePaus = false;
    ui->start_pushbutton->setEnabled(false);

    m_qipan->clearBoard();  // 清空棋盘
    m_qipan->update();

    ui->restart_pushbutton->setEnabled(true);
    ui->restart_pushbutton->setText("重新开始");

    remainingTime = 300;  // 初始化倒计时为5分钟
    updateTimeDisplay();

    timer->start(1000);  // 启动计时器，每秒更新一次
}

// 点击重新开始按钮时的操作
void GoBang::restart_pushbutton_clicked()
{
    if (gameOver)
    {
        qDebug() << "重新开始游戏";

        gameStart = false;
        gameOver = false;
        gamePaus = false;
        remainingTime = 300;  // 重置剩余时间为5分钟
        ui->lcdNumber->display(remainingTime);

        m_qipan->clearBoard();
        m_qipan->update();

        ui->start_pushbutton->setEnabled(true);
        ui->restart_pushbutton->setEnabled(false);

        timer->stop();
    }
    else
    {
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this, "确认重新开始", "是否确认重新开始游戏？", QMessageBox::Yes | QMessageBox::No);

        if (reply == QMessageBox::Yes)
        {
            gameStart = false;
            gameOver = false;
            gamePaus = false;
            remainingTime = 300;  // 重置剩余时间为5分钟
            ui->lcdNumber->display(remainingTime);

            m_qipan->clearBoard();
            m_qipan->update();

            ui->start_pushbutton->setEnabled(true);
            ui->restart_pushbutton->setEnabled(false);

            timer->stop();
        }
    }
}

// 点击悔棋按钮时的操作
void GoBang::renege_pushbutton_clicked()
{
    if (moveHistoryStack.isEmpty())
    {
        QMessageBox::information(this, "无法悔棋", "没有更多可悔棋的棋子");
        return;
    }

    if (undoCount >= 3)
    {
        QMessageBox::information(this, "悔棋次数已满", "您已经悔棋三次，不能再悔棋了");
        return;
    }

    // 撤销最后一步棋
    QPair<QPair<int, int>, bool> lastMove = moveHistoryStack.pop();
    int row = lastMove.first.first;
    int col = lastMove.first.second;
    bool isPlayerMove = lastMove.second;

    m_qipan->setBoardInfo(row, col, EMPTY);  // 清除该位置的棋子
    m_qipan->update();

    if (isPlayerMove)
    {
        if (!moveHistoryStack.isEmpty())
        {
            QPair<QPair<int, int>, bool> aiMove = moveHistoryStack.pop();
            int aiRow = aiMove.first.first;
            int aiCol = aiMove.first.second;

            m_qipan->setBoardInfo(aiRow, aiCol, EMPTY);  // 撤销AI的棋步
            m_qipan->update();
        }
    }
    else
    {
        if (!moveHistoryStack.isEmpty())
        {
            QPair<QPair<int, int>, bool> playerMove = moveHistoryStack.pop();
            int playerRow = playerMove.first.first;
            int playerCol = playerMove.first.second;

            m_qipan->setBoardInfo(playerRow, playerCol, EMPTY);  // 撤销玩家的棋步
            m_qipan->update();
        }
    }

    undoCount++;  // 增加悔棋次数
    gameOver = false;
    gameStart = true;
    gamePaus = false;

    // 重新启动计时器
    if (remainingTime > 0 && !timer->isActive())  // 如果计时器已经停止且剩余时间大于0
    {
        timer->start(1000);  // 启动计时器，每秒更新一次
    }
}

// 保存每一步棋的状态
void GoBang::saveMove(int row, int col, bool isPlayerMove)
{
    if (undoCount >= 3)  // 如果悔棋次数已满，不再记录
        return;

    QPair<int, int> position(row, col);
    QPair<QPair<int, int>, bool> move(position, isPlayerMove);

    moveHistoryStack.push(move);  // 将当前棋步加入历史栈
}

// 更新倒计时显示
void GoBang::updateTimer()
{
    if (remainingTime > 0)
    {
        remainingTime--;  // 每秒减少剩余时间
        updateTimeDisplay();  // 更新显示
    }

    if (remainingTime == 0)  // 如果时间到达5分钟，游戏结束
    {
        gameOver = true;
        QMessageBox::information(this, "游戏结束", "游戏超时，AI获胜");
        ui->start_pushbutton->setEnabled(true);  // 启用开始按钮
        ui->restart_pushbutton->setEnabled(false);  // 禁用重新开始按钮
        timer->stop();  // 停止计时器
    }
}

// 更新LCD显示时间
void GoBang::updateTimeDisplay()
{
    int minutes = remainingTime / 60;
    int seconds = remainingTime % 60;
    ui->lcdNumber->display(QString("%1:%2").arg(minutes, 2, 10, QChar('0')).arg(seconds, 2, 10, QChar('0')));
}

